package com.lgmshare.k3.ui;

import android.app.Activity;
import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;
import androidx.lifecycle.ProcessLifecycleOwner;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelStore;

import com.lgmshare.component.logger.Logger;

/**
 * 全局ViewMode持有
 */
public class AppUIKit {

    private static final String TAG = "AppUIKit";

    private static Application sApplication;
    private static ViewModelProvider sViewModelProvider;
    private static ViewModelStore sViewModelStore;

    private boolean isBackground = true;

    public void init(Application application) {
        sApplication = application;
        ViewModelProvider.Factory factory = ViewModelProvider.AndroidViewModelFactory.getInstance(sApplication);
        sViewModelStore = new ViewModelStore();
        sViewModelProvider = new ViewModelProvider(sViewModelStore, factory);
        //应用前后台监听
        ProcessLifecycleOwner.get().getLifecycle().addObserver(new LifecycleObserver() {
            @OnLifecycleEvent(Lifecycle.Event.ON_START)
            public void onForeground() {
                Logger.d(TAG, "应用进入前台");
                isBackground = false;
            }

            @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
            public void onBackground() {
                Logger.d(TAG, "应用进入后台");
                isBackground = true;
            }
        });
    }

    /**
     * 当{@link androidx.lifecycle.ViewModel} 需要跨{@link Activity} 共享数据时使用
     */
    public static <T extends ViewModel> T getAppScopeViewModel(@NonNull Class<T> modelClass) {
        if (!AppScopeViewModel.class.isAssignableFrom(modelClass)) {
            throw new IllegalArgumentException("the model class should be subclass of AppScopeViewModel");
        }
        return sViewModelProvider.get(modelClass);
    }

    public static void cleanScopeViewModel() {
        sViewModelStore.clear();
    }
}
